package com.carpedil.demo.controller;

import com.auth0.jwt.JWT;
import com.carpedil.demo.common.ResponseCode;
import com.carpedil.demo.common.ResultView;
import com.carpedil.demo.po.User;
import com.carpedil.demo.service.UserService;
import com.carpedil.demo.utils.JwtUtil;
import com.carpedil.demo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/** @author Administrator */
@RestController
@RequestMapping("/user")
public class UserController {

  @Autowired
  @Qualifier("userService")
  private UserService userService;

  @GetMapping("/verify")
  public Object verify(HttpServletRequest request) {
    String authorization = request.getHeader("authorization");
    // 截取前台传过来数据中的Bearer
    String token = authorization.substring(7);
    int userId = 0;

    userId = JWT.decode(token).getClaim("id").asInt();

    User user = userService.getUserById(userId);
    ResultView rv = null;
    if (user != null) {
      rv = new ResultView(ResponseCode.WEB_200, "success", user);
    }
    return rv;
  }

  @PostMapping("/login")
  public Object login(User user, HttpServletResponse response) {
    System.out.println("user = " + user);
    User u = userService.login(user);
    ResultView rv = null;
    if (u != null) {
      rv = new ResultView(ResponseCode.WEB_200, "success", u);
      // 生成jwt token
      String token = JwtUtil.createJwT(6000000, u);
      response.setHeader("Authorization", token);
    }
    return rv;
  }

  @PostMapping("/findUsers")
  public Object getAllUsers() {
    List<UserVo> users = userService.findAllUsers();
    ResultView rv = null;
    if (users != null) {
      rv = new ResultView(ResponseCode.WEB_200, "success", users);
    }
    return rv;
  }
}
